package com.genius.adminmanager.menu.service;

import java.sql.SQLException;
import java.util.ArrayList;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.genius.adminmanager.menu.entity.MenuJson;
import com.genius.adminmanager.other.entity.ModeJson;
import com.genius.adminmanager.other.entity.ResponseJson;
import com.genius.workflow.config.DefaultConfiguration;
import com.genius.workflow.ehcache.CacheUtils;
import com.genius.workflow.page.PageResult;
import com.genius.workflow.page.SqlLang;
import com.genius.workflow.util.ConnectionException;
import com.genius.workflow.util.DBClosedException;
import com.genius.workflow.util.DBTools;
import com.genius.workflow.util.DBUtils;
import com.genius.workflow.util.Pattern;
import com.genius.workflow.util.TimeDiff;
import com.genius.workflow.util.TreeUtils;

public class MenuService {
	/*
	 * 如果有排序字段，就默认按排序字段查询
	 */
	public static String getSelectPageSql(String field,String table,int page,int limit,String asc,String ascField){
		String newField = "SQL_CALC_FOUND_ROWS "+field;
    	String newTable = "";
		if(StringUtils.contains(table, "select")){
			newTable = "("+table+")ta1";
		}else{
			newTable = table;
		}
		String orderby = "";
		if(ascField!=null)
			orderby = "order by "+ascField+" "+asc;
    	String sql = "select "+newField+" from "+newTable+" "+orderby+" limit "+(page-1)*limit+","+limit;
    	
    	return sql;
	}
	public static PageResult getBodyList(SqlLang sql) throws ConnectionException, DBClosedException, SQLException{
		PageResult result = DBUtils.selectByCount(sql);
		
		return result;
	}
	public static String getSelectPageByHighWhereSql(String field,int page,int limit,JSONObject search){
		String newField = "SQL_CALC_FOUND_ROWS "+field;
		String where = " where userId !='100'";
		if(!search.isEmpty()){
			for(String key:search.keySet()){
				String value = search.getString(key);
				if(StringUtils.isNotBlank(value))
					where += " and "+key+"="+"'"+value+"'";
			}
		}
		
		String newTable = "";
		String table = "t_user";
		if(StringUtils.contains(table.toLowerCase(), "select")){
			newTable = "("+table+")ta1";
		}else{
			newTable = table;
		}
		String sql = "select "+newField+" from "+newTable+where+" limit "+(page-1)*limit+","+limit;
    	
    	return sql;
	}
	public static String getSelectPageByOrderSql(String field,int page,int limit,String ascField,String asc,JSONObject search){
		String newField = "SQL_CALC_FOUND_ROWS "+field;
		String table = "t_user";
		String where = " where userId !='100'";
		if(!search.isEmpty()){
			for(String key:search.keySet()){
				String value = search.getString(key);
				if(StringUtils.isNotBlank(value))
					where += " and "+key+"="+"'"+value+"'";
			}
		}
    	
		String newTable = "";
		if(StringUtils.contains(table, "select")){
			newTable = "("+table+")ta1";
		}else{
			newTable = table;
		}
    	String sql = "select "+newField+" from "+newTable+where+" order by "+ascField+" "+asc+" limit "+(page-1)*limit+","+limit;
    	
    	return sql;
	}
	public static void loadPlatformModel(String lastMenuId,String lastPid,JSONObject json,String nowState,String labelName,String typeP) throws ConnectionException, DBClosedException, SQLException{
		String headField = ModeJson.moduleId+","+ModeJson.moduleName+","+ModeJson.moduleSelectMenuId+","+ModeJson.moduleAddMenuId+","+ModeJson.moduleEditMenuId+","+
					ModeJson.moduleBatchdelMenuId+","+ModeJson.moduleExportMenuId+","+ModeJson.moduleUrl+","+ModeJson.field;
		String table = "t_mode";
		String sql = "select "+headField+" from "+table+" where " +ModeJson.moduleId+" = ?";
		
		String menuId = json.getString(MenuJson.menuId);//上级菜单
		String name = json.getString(MenuJson.name);
		String type = typeP==null?json.getString(MenuJson.type):typeP;
		String url = json.getString(MenuJson.url);
		String place = json.getString(MenuJson.place);
		String modelValue = json.getString("modelValue");
		String createTime = TimeDiff.getNowTime(Pattern.yyyyMMddHHmmss);
		String status = json.containsKey(MenuJson.status)?"1":"0";
		
		JSONObject selectJson = DBUtils.select(sql,new String[]{modelValue});
		if(selectJson!=null){
			String moduleSelectMenuId = selectJson.getString(ModeJson.moduleSelectMenuId);
			String moduleAddMenuId = selectJson.getString(ModeJson.moduleAddMenuId);
			String moduleEditMenuId = selectJson.getString(ModeJson.moduleEditMenuId);
			String moduleBatchdelMenuId = selectJson.getString(ModeJson.moduleBatchdelMenuId);
			String moduleExportMenuId = selectJson.getString(ModeJson.moduleExportMenuId);
			String modeField = selectJson.getString(ModeJson.field);
			//为保证唯一性，这里最好校验一下是否已经创建了此模块  查看上级菜单的子菜单下是否已经有了此模块
			String leadMenuSql = "select "+MenuJson.menuId+","+MenuJson.state+" from t_menu where "+MenuJson.menuId+"='"+moduleSelectMenuId+"' and "+MenuJson.parentId+"='"+menuId+"'";
			JSONObject leadJson = DBUtils.select(leadMenuSql);
			
			if(leadJson==null){
				MenuUtils.addMenuByPlatform(moduleSelectMenuId,"", name, nowState, url, menuId, place, type, labelName, createTime, status);
				//leadJson = DBUtils.select(leadMenuSql);
				MenuUtils.insertMenuRAM(null, lastMenuId,"",lastPid,moduleSelectMenuId, name, menuId);
			}
			
//			String leadMenuId = leadJson.getString(MenuJson.menuId);
			String leadMenuState = Integer.parseInt(nowState)+1+"";
			//插入四个按钮
			MenuUtils.addMenuBtn(moduleAddMenuId, "layui-icon-add-circle", "新增", leadMenuState, "add", moduleSelectMenuId, "0", "button", labelName, createTime, status);
			MenuUtils.addMenuBtn(moduleEditMenuId, "layui-icon-edit", "编辑", leadMenuState, "edit", moduleSelectMenuId, "0", "button", labelName, createTime, status);
			MenuUtils.addMenuBtn(moduleBatchdelMenuId, "layui-icon-delete", "删除", leadMenuState, "batchdel", moduleSelectMenuId, "0", "button", labelName, createTime, status);
			MenuUtils.addMenuBtn(moduleExportMenuId, "layui-icon-template-1", "导出", leadMenuState, "export", moduleSelectMenuId, "0", "button", labelName, createTime, status);
			
	    	//向t_menu_field 中插入模块字段
	    	JSONObject parmsJson = new JSONObject();
	    	parmsJson.put(MenuJson.menuId, moduleSelectMenuId);
	    	parmsJson.put(MenuJson.field, modeField);
	    	MenuUtils.addFieldByMenuId(parmsJson);
		
		}
	}
	public static JSONObject selectUrlByMenuId(JSONObject json,JSONObject response) throws ConnectionException, DBClosedException, SQLException{
//		String menuId = json.getString(MenuJson.menuId);
		String selectField = MenuJson.url;
		String table = "t_menu";
		String whereField = MenuJson.menuId;
		String sql = DBTools.getSelectAndWhereSql(selectField, table, whereField);
		String [] params = DBTools.getSelectParms(whereField, json);
		JSONObject select = DBUtils.select(sql, params);
		if(select != null ){
			response.put(ResponseJson.msg, "查询菜单地址成功");
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.data, select);
		}else{
			response.put(ResponseJson.msg, "查询菜单地址失败");
			response.put(ResponseJson.status, ResponseJson.status_Failed);
		}
		return response;
		
	}
	public static void loadMenusRAM(){
		String table = "t_menu";
    	String field = MenuJson.menuId+","+MenuJson.menuId+","+MenuJson.name+","+MenuJson.parentId+","+MenuJson.type;
    	String where = "";
    	String orderBy = " order by "+MenuJson.place;
    	try {
        	JSONArray data = TreeUtils.getTree(MenuJson.menuId, field,MenuJson.parentId,table, MenuJson.state,MenuJson.resource,where, orderBy);
    		JSONArray root = new JSONArray();
    		
    		JSONObject root1 = new JSONObject();
    		JSONArray root1Arr = new JSONArray();
    		root1.put("value", "-1");
    		root1.put("name", "一级目录");
    		root1.put("pId", "-1");
    		for(int i = 0;i<data.size();i++){
    			JSONObject datas = data.getJSONObject(i);
    			datas.put("value", datas.getString(MenuJson.menuId));
    			datas.put("name", datas.getString(MenuJson.name));
    			datas.put("pId", datas.getString(MenuJson.parentId));

    			JSONArray children = new JSONArray();
    			for(int index = 0;index<datas.getJSONArray("children").size();index++){
    				JSONObject childrens = changeKey(datas.getJSONArray("children").getJSONObject(index));
    				children.add(childrens);
    			}
    			datas.put("children", children);
    			root1Arr.add(removeKey(datas));
    		}
    		root1.put("children", root1Arr);
    		root.add(root1);
    		CacheUtils.cacheUtils().addCache(DefaultConfiguration.menuRAM);
    		CacheUtils.cacheUtils().addElement(DefaultConfiguration.menuRAM, DefaultConfiguration.menuRAM_tree, root);
		}  catch (ConnectionException e) {
			e.printStackTrace();
		} catch (DBClosedException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	private static JSONObject changeKey(JSONObject datas){
		if(datas.getString(MenuJson.type).equals("按钮")){
			return null;
		}
		datas.put("value", datas.getString(MenuJson.menuId));
		datas.put("name", datas.getString(MenuJson.name));
		datas.put("pId", datas.getString(MenuJson.parentId));
		
		if(datas.containsKey("children")){
			JSONArray children = new JSONArray();
			for(int index = 0;index<datas.getJSONArray("children").size();index++){
				JSONObject childrens = changeKey(datas.getJSONArray("children").getJSONObject(index));
				//三级目录 去掉按钮 一级
				if(childrens != null){
					children.add(childrens);
					if(childrens.containsKey("children")){
						if(childrens.getJSONArray("children").size()==0)
							childrens.remove("children");
					}
				}
			}
				datas.put("children", children);
		}
		return removeKey(datas);
	}
	private static JSONObject removeKey(JSONObject datas){
		String keys = "value,name,children,pId";
		ArrayList<String> removeKeys = new ArrayList<>();
		for(String key:datas.keySet()){
			if(!keys.contains(key)){
				removeKeys.add(key);
			}
		}
		for(String key:removeKeys){
			datas.remove(key);
		}
		return datas;
	}
}
